<!--
 * 主内容区域组件
 * 功能：包含对话区域和侧边卡片区域的主要布局容器
 * 作者：MetasoCreator Team
 * 创建时间：2025-01-19
 * 修改时间：2025-01-19
-->

<template>
  <div class="main-layout">
    <!-- 主内容区 -->
    <div class="main-content">
      <div class="content-wrapper">
        <!-- 主对话区域 -->
        <div class="chat-section">
          <ChatContainer 
            class="chat-container"
            :messages="appStore.chatMessages"
            :loading="appStore.isLoading"
            @send-message="handleChat"
            @search="handleSearch"
          />
        </div>
      </div>
    </div>

    <!-- 侧边链接卡片区域 -->
    <SidebarContainer 
      :collapsed="isSidebarCollapsed"
      :searchSources="appStore.linkCards"
      @source-click="handleSourceClick"
      @clear-sources="handleClearSources"
      class="sidebar"
      :class="{ collapsed: isSidebarCollapsed }"
    />

    <!-- 移动端侧边栏切换按钮 -->
    <el-button
      v-if="isMobile"
      class="sidebar-toggle"
      type="primary"
      :icon="isSidebarCollapsed ? Expand : Fold"
      circle
      @click="toggleSidebar"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Expand, Fold } from '@element-plus/icons-vue'
import { useAppStore } from '../stores/counter'
import ChatContainer from './chat/ChatContainer.vue'
import SidebarContainer from './sidebar/SidebarContainer.vue'
import { searchAPI, qaAPI, readerAPI } from '../api'

// 使用状态管理
const appStore = useAppStore()

// 响应式数据
const windowWidth = ref(window.innerWidth)
const isSidebarCollapsed = ref(false)

// 计算属性
const isMobile = computed(() => windowWidth.value < 768)
const isTablet = computed(() => windowWidth.value >= 768 && windowWidth.value < 1200)
const isDesktop = computed(() => windowWidth.value >= 1200)

// 方法
const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
  appStore.toggleSidebar()
}

const handleSourceClick = async (source) => {
  console.log('点击来源:', source)
  
  try {
    // 如果是网页链接，可以使用阅读器API获取内容
    if (source.url && source.url.startsWith('http')) {
      appStore.setLoading(true)
      const result = await readerAPI.readUrl(source.url)
      
      if (result.success) {
        // 将读取的内容添加到聊天记录中
        appStore.addChatMessage({
          role: 'system',
          content: `已读取网页内容：${result.title}\n\n${result.markdown}`,
          source: source
        })
      }
    } else {
      // 直接打开链接
      window.open(source.url, '_blank')
    }
  } catch (error) {
    console.error('处理源点击失败:', error)
  } finally {
    appStore.setLoading(false)
  }
}

// 处理清空数据来源
const handleClearSources = () => {
  // 清空store中的linkCards
  appStore.linkCards.splice(0)
}

// 处理搜索请求
const handleSearch = async (query, scope = 'webpage') => {
  try {
    appStore.setLoading(true)
    appStore.addSearchHistory(query)
    
    // 添加用户消息到聊天记录
    appStore.addChatMessage({
      role: 'user',
      content: query,
      type: 'user',
      mode: scope === 'scholar' ? 'academic_search' : 'web_search'
    })
    
    let result
    switch (scope) {
      case 'scholar':
        result = await searchAPI.academicSearch(query)
        break
      case 'image':
      case 'video':
      case 'podcast':
        result = await searchAPI.mediaSearch(query, scope)
        break
      default:
        result = await searchAPI.webSearch(query)
    }
    
    console.log('搜索 API 返回结果:', result)
    
    // 修改判断逻辑：检查result是否存在且有数据
    if (result && (result.data || result.choices || result.answer || result.results)) {
      const responseData = result.data || result
      const searchResults = responseData.results || result.results || []
      appStore.setSearchResults(searchResults)
      
      // 处理OpenAI格式的响应数据
      let content = '抱歉，没有获取到有效回复'
      let sources = []
      
      if (responseData.choices && responseData.choices.length > 0) {
        const choice = responseData.choices[0]
        if (choice.message && choice.message.content) {
          content = choice.message.content
        }
        // 从citations中提取sources
        if (choice.message && choice.message.citations) {
          sources = choice.message.citations
        }
      } else if (responseData.answer) {
        content = responseData.answer
        sources = responseData.sources || []
      } else if (searchResults.length > 0) {
        content = `找到 ${searchResults.length} 个相关结果`
        sources = searchResults
      }
      
      // 将搜索结果添加到聊天记录
      appStore.addChatMessage({
        role: 'assistant',
        content: content,
        type: 'ai',
        mode: scope === 'scholar' ? 'academic_search' : 'web_search',
        sources: sources,
        searchResults: searchResults,
        query: query
      })
      
      // 更新侧边栏链接卡片
      if (sources && sources.length > 0) {
        // 清空现有卡片
        appStore.linkCards.splice(0)
        
        // 添加新的搜索结果卡片
        sources.forEach((source, index) => {
          appStore.addLinkCard({
            id: Date.now() + index,
            title: source.title || `搜索结果 ${index + 1}`,
            url: source.url || source.link || '#',
            description: source.snippet || source.description || source.content || '暂无描述',
            source: source.source || source.domain || '未知来源',
            publishedDate: source.published_date || source.date,
            contentType: source.content_type || 'webpage',
            score: source.score
          })
        })
      }
    } else {
      // 搜索失败时添加错误消息
      appStore.addChatMessage({
        role: 'assistant',
        content: '抱歉，搜索时出现了错误，请稍后重试。',
        type: 'ai',
        mode: scope === 'scholar' ? 'academic_search' : 'web_search',
        error: true
      })
    }
  } catch (error) {
    console.error('搜索失败:', error)
    // 添加错误消息到聊天记录
    appStore.addChatMessage({
      role: 'assistant',
      content: '抱歉，搜索时出现了错误，请稍后重试。',
      type: 'ai',
      mode: scope === 'scholar' ? 'academic_search' : 'web_search',
      error: true
    })
  } finally {
    appStore.setLoading(false)
  }
}

// 处理问答请求
const handleChat = async (message) => {
  try {
    appStore.setLoading(true)
    
    // 添加用户消息
    appStore.addChatMessage({
      role: 'user',
      content: message,
      type: 'user',
      mode: 'qa'
    })
    
    // 准备消息历史
    const messages = appStore.chatMessages.map(msg => ({
      role: msg.role,
      content: msg.content
    }))
    
    // 调用问答API
    const result = await qaAPI.ask(messages, {
      model: appStore.currentModel,
      scope: appStore.searchScope
    })
    
    console.log('QA API 返回结果:', result)
    
    // 修改判断逻辑：检查result是否存在且有数据
    if (result && (result.data || result.choices || result.answer)) {
      const responseData = result.data || result
      let content = '抱歉，没有获取到有效回复'
      let sources = []
      
      // 处理OpenAI格式的响应数据
      if (responseData.choices && responseData.choices.length > 0) {
        const choice = responseData.choices[0]
        if (choice.message && choice.message.content) {
          content = choice.message.content
        }
        // 从citations中提取sources
        if (choice.message && choice.message.citations) {
          sources = choice.message.citations
        }
      } else if (responseData.answer) {
        content = responseData.answer
        sources = responseData.sources || []
      }
      
      // 添加AI回复消息
      appStore.addChatMessage({
        role: 'assistant',
        content: content,
        type: 'ai',
        mode: 'qa',
        sources: sources,
        metadata: responseData.metadata || responseData.usage || {}
      })
      
      // 如果有引用来源，更新侧边栏链接卡片
      if (sources && sources.length > 0) {
        // 清空现有卡片
        appStore.linkCards.splice(0)
        
        // 添加新的引用来源卡片
        sources.forEach((source, index) => {
          appStore.addLinkCard({
            id: Date.now() + index,
            title: source.title || `引用来源 ${index + 1}`,
            url: source.url || source.link || '#',
            description: source.snippet || source.description || source.content || '暂无描述',
            source: source.source || source.domain || '引用来源',
            publishedDate: source.published_date || source.date,
            contentType: source.content_type || 'reference',
            score: source.score
          })
        })
      }
    } else {
      // API调用失败时添加错误消息
      appStore.addChatMessage({
        role: 'assistant',
        content: '抱歉，处理您的请求时出现了错误，请稍后重试。',
        type: 'ai',
        mode: 'qa',
        error: true
      })
    }
  } catch (error) {
    console.error('问答失败:', error)
    appStore.addChatMessage({
      role: 'assistant',
      content: '抱歉，处理您的请求时出现了错误，请稍后重试。',
      type: 'ai',
      mode: 'qa',
      error: true
    })
  } finally {
    appStore.setLoading(false)
  }
}

const handleResize = () => {
  windowWidth.value = window.innerWidth
  
  // 在桌面端自动展开侧边栏
  if (isDesktop.value) {
    isSidebarCollapsed.value = false
  }
  // 在移动端自动收起侧边栏
  else if (isMobile.value) {
    isSidebarCollapsed.value = true
  }
}

// 生命周期
onMounted(() => {
  window.addEventListener('resize', handleResize)
  handleResize() // 初始化
  console.log('MainContent 组件已挂载')
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.main-content {
  margin-top: 60px; /* 为固定的顶部导航栏留出空间 */
  min-height: calc(100vh - 60px);
  background: var(--bg-tertiary);
  padding: 20px;
  transition: all 0.3s ease;
}

.content-container {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
  height: calc(100vh - 100px);
  position: relative;
}

.chat-section {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
  transition: all 0.3s ease;
}

.sidebar-section {
  width: 390px;
  flex-shrink: 0;
  transition: all 0.3s ease;
  transform: translateX(0);
}

.sidebar-section.sidebar-collapsed {
  transform: translateX(100%);
  width: 0;
  overflow: hidden;
}

.sidebar-toggle {
  position: fixed;
  right: 20px;
  bottom: 80px;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.sidebar-toggle:hover {
  transform: scale(1.1);
}

/* 响应式布局 */
@media (max-width: 1199px) {
  .sidebar-section {
    width: 350px;
  }
}

@media (max-width: 767px) {
  .main-content {
    padding: 15px;
  }
  
  .content-container {
    gap: 0;
    height: calc(100vh - 90px);
  }
  
  .chat-section {
    width: 100%;
  }
  
  .sidebar-section {
    position: fixed;
    top: 60px;
    right: 0;
    bottom: 0;
    width: 100%;
    max-width: 400px;
    background: var(--bg-primary);
    box-shadow: -4px 0 12px rgba(0, 0, 0, 0.15);
    z-index: 999;
    padding: 20px;
    overflow-y: auto;
  }
  
  .sidebar-section.sidebar-collapsed {
    transform: translateX(100%);
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 10px;
  }
  
  .sidebar-section {
    width: 100%;
    max-width: none;
    padding: 15px;
  }
  
  .sidebar-toggle {
    right: 15px;
    bottom: 70px;
  }
}

/* 暗色主题适配 */
:root[data-theme="dark"] .main-content {
  background: var(--bg-tertiary);
}

:root[data-theme="dark"] .sidebar-section {
  background: var(--bg-primary);
}

/* 动画效果 */
@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideOutRight {
  from {
    transform: translateX(0);
    opacity: 1;
  }
  to {
    transform: translateX(100%);
    opacity: 0;
  }
}

.sidebar-section:not(.sidebar-collapsed) {
  animation: slideInRight 0.3s ease;
}

.sidebar-section.sidebar-collapsed {
  animation: slideOutRight 0.3s ease;
}
</style>